package com.springboot2.authserver.jwt.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.annotation.Resource;

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Resource
    private PasswordEncoder encoder;

    private String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIIEpAIBAAKCAQEA2pqAgxpVh3SpqimEEuSYVv8m54y6td1guIsULbp0Deihb1I5\n" +
            "RJAjA/Um+stXxhB7Q7m3WC2QjiHgXM2TSlSxlx7a/xnn0pNA1aKWZ9XOl9zt+ADj\n" +
            "SJiCQ/qN1i/vYrM0/a0xce2eLvSbFTJbb2wZmkTi5M8qJlXnzPfv/6O4ruIBgFrd\n" +
            "2m62O1V4dmvf9yz/jc6X2vJKVxMQLiI0QF8AMigvKfHeU4boLwAXl56qpAJxnWOK\n" +
            "ZBg8z2BzzF4SPSOzgOvJxy770ln/i6Z8zQPzy44hX6dLtBeYogPPIm236ZMtx3a/\n" +
            "M7KyWNSqGo5t8Sz9oxXZdQ4xd3pCFFxtjJBEtQIDAQABAoIBAQCurWajXBeb9Yzd\n" +
            "e+8daayRV7EutTU8vXjb/cZSA/tYYdsdqQY50zMnpm1PWcz5Z5IXu/7VZxNrf4ZY\n" +
            "oaxgaOy/ZNh5n6muihv0mca1khNTJibBVXRIPhVZXIyZ6hPPOoPNcOdhsg4EV1DU\n" +
            "zzhhAHA05XaofyGfIGXpUvVjwN+CXXvRbEJ2WiNEIPUHmUpwXzgNa+80iwVSA7JU\n" +
            "ssms/aIMyWG5Y0IXsUDcZTBAdIT1Qo0UNzK3KQcxx3ZjJpbhK2/cqTBORDpAbiaA\n" +
            "+/Jk20BhWz5qM9LI8UFNCxEBj9pNgQkCOi60GeplJ6O1WHbhqp3zsTaiHNrJ8ROr\n" +
            "HoR+ZCQBAoGBAPFr9kZP9FxPXTXhPDkh8I2zI8lG5ZSkbb0ZMQutJPMDrS7XsI2s\n" +
            "VI4gikZE3jCST7jGHFl/AwW2mfO0BIhXZlZHBBkq2I+0ECPmluwz1ALpTcbwAFUR\n" +
            "yQ34/yTTMW5TsIcWISb2mPQesnpqmtJM2XVPcbGmdgcRgBuc/aAJfYyRAoGBAOfN\n" +
            "zYnXJVyq863GUFX9KDlSFUZnBo+LBkpv4cIJD+XdyMFEEuCEN8j6VEeOzFbTArmr\n" +
            "ELgPQw7DSs0p9ov4qBWehj95bmSWOvaOIbHCBwIvoMtaXdixdf2RQicAd9RuaMJd\n" +
            "eLV/7s9cYc9/Keh6eTv/GBlSIttyCuZtHQZ32JflAoGBANCEvFDcrCWy0sI/yUFb\n" +
            "hCcPjCBD4PVy0+nZQVhhcyGGkmV8HF0xdFLR3jx1LSfsp3jjfAb8wgKERhKM8MFG\n" +
            "I/jvG6YVMLll/+7SMpbO6RaepfPmxZK0auBrqQwIcZBmLnlu7rF1moR3oxZCz3hG\n" +
            "sig1tvCG4ziVr/2pqhI5QDxRAoGATLwtQWcuYBnbZvhSWdTfPvJ0RoUOf/A22edl\n" +
            "pbUYRTEBJzFgymAak3aC9dlIvalGqq39b+DlgvqVRYuRqU5cXiPHLzYEnFm7FSmB\n" +
            "7/VaGpgns4mrrXM5qwIuEvktse4G0ejdb7/1D0H2wxjGh8YbYggVMzSkg16iSxtt\n" +
            "01lTIx0CgYA0Rep3ORqPJg+deugtXLUSHBHj1L9bKB0AzLQP932Ikucxfu8XWwT7\n" +
            "xR3tj6I9VXOTx6sIEJqL7YWXZyvr9ETqT1JK8tWg4ZUqJzGgzgA6GgK9zyu1qohC\n" +
            "+ole0nc4FGNuHRgqrVbX6hM6riRGerUVfgzpcs9kctQzv6s2Fxv6QQ==\n" +
            "-----END RSA PRIVATE KEY-----";
    private String publicKey = "-----BEGIN PUBLIC KEY-----\n" +
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2pqAgxpVh3SpqimEEuSY\n" +
            "Vv8m54y6td1guIsULbp0Deihb1I5RJAjA/Um+stXxhB7Q7m3WC2QjiHgXM2TSlSx\n" +
            "lx7a/xnn0pNA1aKWZ9XOl9zt+ADjSJiCQ/qN1i/vYrM0/a0xce2eLvSbFTJbb2wZ\n" +
            "mkTi5M8qJlXnzPfv/6O4ruIBgFrd2m62O1V4dmvf9yz/jc6X2vJKVxMQLiI0QF8A\n" +
            "MigvKfHeU4boLwAXl56qpAJxnWOKZBg8z2BzzF4SPSOzgOvJxy770ln/i6Z8zQPz\n" +
            "y44hX6dLtBeYogPPIm236ZMtx3a/M7KyWNSqGo5t8Sz9oxXZdQ4xd3pCFFxtjJBE\n" +
            "tQIDAQAB\n" +
            "-----END PUBLIC KEY-----";

    @Resource
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Bean
    public JwtAccessTokenConverter tokenEnhancer() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(privateKey);
        converter.setVerifierKey(publicKey);
        return converter;
    }

    @Bean
    public JwtTokenStore tokenStore() {
        return new JwtTokenStore(tokenEnhancer());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore())
                .accessTokenConverter(tokenEnhancer());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("admin")
                .secret(encoder.encode("admin"))
                .scopes("read", "write")
                .autoApprove("read")
                .authorizedGrantTypes("authorization_code", "password", "refresh_token", "client_credentials")
                .accessTokenValiditySeconds(20000)
                .refreshTokenValiditySeconds(20000);

    }
}